from typing import Optional, List
from pydantic import EmailStr
from sqlalchemy import Integer, JSON, BIGINT
from sqlmodel import Field

from src.base.beans import PageParam
from src.base.constants import phone_pattern, ip_pattern
from src.base.enums import SexType
from src.domain.base_model import TenantModel
from src.base.beans import Bigint, Datetime


class SysUserBase(TenantModel):
    user_id: Optional[Bigint] = Field(default=None, primary_key=True, description="用户序号", sa_type=BIGINT,
                                      sa_column_kwargs={"comment": "用户序号", })
    user_name: Optional[str] = Field(default=None, description="用户名称", sa_column_kwargs={"comment": "用户名称"})
    password: Optional[str] = Field(default=None, description="用户密码", sa_column_kwargs={"comment": "用户密码"})
    nick_name: Optional[str] = Field(default=None, description="用户昵称", sa_column_kwargs={"comment": "用户昵称"})
    email: Optional[EmailStr] = Field(default=None, description="用户邮箱", sa_column_kwargs={"comment": "用户邮箱"})
    phone: Optional[str] = Field(default=None, description="手机号码", regex=phone_pattern,
                                 sa_column_kwargs={"comment": "手机号码"})
    sex: Optional[SexType] = Field(default=None, description="用户性别", sa_type=Integer,
                                   sa_column_kwargs={"comment": "用户性别", "server_default": "0"})
    avatar: Optional[str] = Field(default=None, description="用户头像", sa_column_kwargs={"comment": "用户头像"})
    user_type: Optional[str] = Field(default=None, description="用户类型", sa_column_kwargs={"comment": "用户类型"})
    login_time: Optional[Datetime] = Field(default=None, description="最后登录时间",
                                           sa_column_kwargs={"comment": "最后登录时间"})
    login_ip: Optional[str] = Field(default=None, description="登录IP", regex=ip_pattern,
                                    sa_column_kwargs={"comment": "登录IP"})

    dept_ids: Optional[List[Bigint]] = Field(default=None, description="部门id", sa_type=JSON, )
    post_ids: Optional[List[Bigint]] = Field(default=None, description="岗位id", sa_type=JSON, )


class SysUser(SysUserBase, table=True):
    __tablename__ = "sys_user"
    # extend_existing ： 表结构已存在，不需要创建
    __table_args__ = {'extend_existing': True, 'comment': '用户表'}


class SysUserReq(SysUserBase, PageParam):
    role_ids: Optional[List[Bigint]] = Field(default=None, description="角色id")
    create_time_range: Optional[list[str]] = Field(default=None, description="创建时间范围")
    update_time_range: Optional[list[str]] = Field(default=None, description="更新时间范围")


class SysUserResp(SysUserBase):
    roleCodes: Optional[list[str]] = Field(default=None, description="角色序号", )
    role_ids: Optional[List[Bigint]] = Field(default=None, description="角色id")
    # dept_id: Optional[Bigint] = Field(default=None, description="部门id")
    # dept_name: Optional[str] = Field(default=None, description="部门名称")
    # dept_pid: Optional[Bigint] = Field(default=None, description="部门父id")
